package weifei.live.simulation.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import weifei.live.simulation.entity.ChatGroup;
import weifei.live.simulation.entity.GroupMember;
import weifei.live.simulation.service.AdminerService;
import weifei.web.Result;


@RestController
@RequestMapping("/adminer")
public class GroupAdminerController
{

    @Autowired
    private AdminerService adminerService;

    @Autowired
    private ChatGroup dao_group;

    // 此处有 登录拦截
    @PostMapping("/createGroup")
    @Transactional
    public Result createGroup(@Valid @RequestBody ChatGroup group)
    {
        var owner_id = group.getOwnerId();
        var group_name = group.getName();

        QueryWrapper<ChatGroup> qw_group = new QueryWrapper<>();
        qw_group.eq(ChatGroup.Column.OwnerID.getName(), owner_id);
        qw_group.eq(ChatGroup.Column.Name.getName(), group_name);
        var g = this.dao_group.selectOne(qw_group);
        if (g != null)
            return Result.failed("用户" + owner_id + "已有同名群聊");

        // 不直接 group.insert() 是因为 可能有 ownerId 与 groupName 以外的东西
        ChatGroup cg = new ChatGroup(owner_id, group_name);
        if (!cg.insert())
            return Result.exception("创建群聊失败，数据库出错");

        /* 无用的
        g = cg.selectOne(this.qw_group);
        var owner = new GroupMember(g.getId(), owner_id);
        owner.setCapacity(GroupMember.Capacity.Owner);
        if (!owner.insert())
            throw new RuntimeException("群主插入群成员表失败");
        */

        return Result.success("创建成功");
    }
}

